package com.momomian.admin.generator.code;



import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义生成转换类
 * 实现生成 tar.setX(src.getX());
 * 解放双手
 * 更多推荐： GenerateAllSetter插件 可使用选中一个对象 之后alt+enter 来生成setter、
 *                                 在一个有入参和出参的方法使用这个快捷键可以生成转换tar.setX(src.getX());
 */
public class ConverterUtil {



    public static Set<String> getFieldName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        Set<String> fieldNames = new LinkedHashSet<>();

        for (Field field : fields) {

            fieldNames.add(field.getName());
        }
        return fieldNames;
    }

    public static Set<String> getAllMethods(Object o) {
        Method[] methods = o.getClass().getMethods();
        Set<String> methodNames = new LinkedHashSet<>();
        for (Method method : methods) {
            methodNames.add(method.getName());
        }
        return methodNames;
    }


    public static Set<String> filterMethodsByPrefix(Set<String> methodNames,String prefix){
        return methodNames.stream().filter(x -> x.startsWith(prefix)).collect(Collectors.toSet());
    }

    /**
     * 字段转set方法名
     * @param filedName
     * @return
     */
    public static String getSetterMethodNameByFiled(String filedName){
        return "set" + toUpperCaseFirstOne(filedName);
    }

    /**
     * 字段转get方法名
     * @param filedName
     * @return
     */
    public static String getGetterMethodNameByFiled(String filedName){
        return "get" + toUpperCaseFirstOne(filedName);
    }

    /**
     * 首字母转大写
     * @param s
     * @return
     */
    public static String toUpperCaseFirstOne(String s){
        if(Character.isUpperCase(s.charAt(0))) {
            return s;
        } else {
            return Character.toUpperCase(s.charAt(0)) + s.substring(1);
        }
    }

    public static void print(Object srcObject,Object tarObject){

        Set<String>  dtoFieldName = getFieldName(srcObject);
        Set<String>  voFieldName = getFieldName(tarObject);
        removeSomeFiled(voFieldName);
        String tarName = "tar";
        String srcName = "src";
        StringBuilder sb = new StringBuilder();
        for (String name : voFieldName) {
            if(dtoFieldName.contains(name)){
                sb.append(tarName).append(".").append(getSetterMethodNameByFiled(name)).append("(")
                        .append(srcName).append(".").append(getGetterMethodNameByFiled(name)).append("());\n");
            }
        }
        System.out.println(sb.toString());
    }

    private static void removeSomeFiled(Set<String> voFieldName) {
        voFieldName.remove("serialVersionUID");
    }

}
